package com.sf.asp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sf.asp.entity.RolePermission;
import com.sf.asp.dao.RolePermissionMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sf.asp.entity.dto.RolePermissionDTO;
import com.sf.asp.service.RolePermissionService;
import com.sf.asp.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jins
 * @since 2021-11-24
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements RolePermissionService {

    public RolePermissionServiceImpl(RolePermissionMapper permissionMapper){
        this.rolePermissionMapper = permissionMapper;
    }

    private final RolePermissionMapper rolePermissionMapper;

    @Override
    public List<RolePermission> listByRoleId(Integer roleId) {
        LambdaQueryWrapper<RolePermission> query = new LambdaQueryWrapper<>();
        query.eq(RolePermission::getRoleId,roleId);
        return rolePermissionMapper.selectList(query);
    }

    @Override
    public void save(RolePermissionDTO rolePermission) {
        List<RolePermission> rolePermissions = new ArrayList<>();
        RolePermission obj ;

        for (Integer permissionId : rolePermission.getPermissions()){
            obj = new RolePermission();
            obj.setPermissionId(permissionId);
            obj.setRoleId(rolePermission.getRoleId());
            obj.setCreateTime(LocalDateTime.now());
            obj.setCreateUser(1);
            rolePermissions.add(obj);
        }

        //先删除
        LambdaQueryWrapper<RolePermission> query = new LambdaQueryWrapper<>();
        query.eq(RolePermission::getRoleId,rolePermission.getRoleId());
        rolePermissionMapper.delete(query);

        rolePermissionMapper.batchSave(rolePermissions);
    }
}
